package com.sky.handler;

import com.sky.exception.BaseException;
import com.sky.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 全局异常处理器，处理项目中抛出的业务异常
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 捕获业务异常
     * @param ex
     * @return
     */
    @ExceptionHandler
    public Result exceptionHandler(BaseException ex){
        log.error("异常信息：{}", ex.getMessage());
        return Result.error(ex.getMessage());
    }

    /**
     * 处理sql异常
     * @param ex
     * @return
     */
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)  //指定要处理哪种异常
    public Result doSQLIntegrityConstraintViolationException(SQLIntegrityConstraintViolationException ex){
        String message = ex.getMessage(); //Duplicate entry 'aaa' for key 'dept.name'
        log.error(message);
        ex.printStackTrace();
        if (message.contains("Duplicate entry")) {
            String msg = message.split(" ")[2]; //'aaa'
            return Result.error(msg + "已存在！！");
        }
        return Result.error("出错啦！！！请联系管理员！！！");
    }

}
